<template>
  <div>
    <el-upload
      :action="policy.host"
      :data="postData"
      :show-file-list="false"
      :limit="1"
      ref="upload"
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload">
      <el-button size="small" type="primary" plain>上传图片</el-button>
    </el-upload>
  </div>
</template>

<script lang="ts">
  import uuid from 'uuid'
  import { Vue, Component, Prop } from 'vue-property-decorator'
  import { Getter } from 'vuex-class'

  @Component()
  export default class Uploader extends Vue {
    @Getter policy
    @Prop() value

    changeImageSrc (src) {
      this.$emit('input', src)
      this.$emit('success')
    }

    get postData () {
      return {...this.policy}
    }

    handleUploadSuccess (res) {
      this.$utils.tips(res)
      this.changeImageSrc(res.data.path)
      this.$refs.upload.clearFiles()
    }

    beforeUpload (file) {
      let filename = file.name
      let existName = filename.substr(filename.lastIndexOf('.'))
      this.postData.key = uuid() + existName
      this.postData.callback = window.btoa(JSON.stringify({
        callbackUrl: 'https://1894469675823662.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/oss/callback/',
        callbackBody: '{"object":${object}}',
        callbackBodyType: 'application/json'
      }))
    }
  }
</script>

<style lang="less" scoped>

</style>
